﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using MediaPortal.DeployTool;
using Microsoft.WindowsServerSolutions.Common.UI.TaskDialog;
using Microsoft.WindowsServerSolutions.Wizards;

namespace TV4Home.Server.Vail.AddIn.Wizards.InstallTVServer
{
    public partial class InstallTVServerWizard : WizardForm
    {
        public InstallTVServerWizard()
        {
            InitializeComponent();

            this.WizardTitle = "Install MediaPortal TV Server";
            this.WizardIcon = Properties.Resources.SetupTv;
        }

        #region WPWelcome
        private void wpWelcome_GettingNextPage(object sender, GettingTargetPageEventArgs e)
        {
            InstallationProperties.Instance.Set("InstallType", "tvserver_master");
        }
        #endregion

        #region WPInfo
        private void wpInfo_PageValidating(object sender, ValidatingEventArgs e)
        {
            // check internet connection and proceed if available
            e.IsValid = MediaPortal.DeployTool.InstallationChecks.InternetChecker.CheckConnection();

            if (!e.IsValid)
                TaskMessageBox.Show("Please connect your server to the Internet and try again.", "Error", "Couldn't connect to the Internet!", TaskDialogButtons.Ok, TaskDialogIcon.Error);
        }
        #endregion

        #region WPDatabaseType
        private void wpDatabaseType_PageInitializing(object sender, EventArgs e)
        {
            wpDatabaseType.DatabaseTypeButtonClicked += (sender2, e2) =>
                                                            {
                                                                this.WizardNextButton.Enabled = true;
                                                                this.WizardNextButton.PerformClick();
                                                            };
        }

        private void wpDatabaseType_PageEnter(object sender, EventArgs e)
        {
            this.WizardNextButton.Enabled = false;
        }

        private void wpDatabaseType_GettingNextPage(object sender, GettingTargetPageEventArgs e)
        {
            // remove DBMSDir key if it exists, so that the next page can set the correct directory (e.g. when the user has changed the DB selection)
            InstallationProperties.Instance.Remove("DBMSDir");

            switch (wpDatabaseType.SelectedDatabaseType)
            {
                case WPDatabaseTypeControl.DatabaseType.MSSQL:
                    e.TargetPage = wpDatabaseSettings;
                    InstallationProperties.Instance.Set("DBMSType", "msSQL2005");
                    break;
                case WPDatabaseTypeControl.DatabaseType.MySQL:
                    e.TargetPage = wpDatabaseSettings;
                    InstallationProperties.Instance.Set("DBMSType", "mysql");
                    break;
                case WPDatabaseTypeControl.DatabaseType.SQLAlreadyPresent:
                    e.TargetPage = wpTvServerSettings;
                    InstallationProperties.Instance.Set("DBMSType", "DBAlreadyInstalled");
                    break;
            }
        }
        #endregion

        #region WPDatabaseSettings
        private void wpDatabaseSettings_PageEnter(object sender, EventArgs e)
        {
            wpDatabaseSettings.InitializeUI();
        }

        private void wpDatabaseSettings_GettingNextPage(object sender, GettingTargetPageEventArgs e)
        {
            InstallationProperties.Instance.Set("DBMSDir", wpDatabaseSettings.DBDirectory);
            InstallationProperties.Instance.Set("DBMSPassword", wpDatabaseSettings.DBUserPassword);
            InstallationProperties.Instance.Set("ConfigureDBMSFirewall", wpDatabaseSettings.ConfigureFirewallDB ? "1" : "0");
        }
        #endregion

        #region WPTVServerSettings
        private void wpTvServerSettings_PageEnter(object sender, EventArgs e)
        {
            wpTvServerSettings.InitializeUI();
        }

        private void wpTvServerSettings_GettingNextPage(object sender, GettingTargetPageEventArgs e)
        {
            InstallationProperties.Instance.Set("TVServerDir", wpTvServerSettings.TvServerDirectory);
            InstallationProperties.Instance.Set("ConfigureTVServerFirewall", wpTvServerSettings.ConfigureFirewallTVServer ? "1" : "0");
        }
        #endregion

        #region WPInstallation

        private string nextButtonText;
        private void wpInstallation_PageEnter(object sender, EventArgs e)
        {
            wpInstallation.PopulateListView();

            nextButtonText = this.WizardNextButton.Text; // save for later
            this.WizardNextButton.Text = "Install";
        }

        private bool firstOnNext = true;
        private bool installSucceeded = false;

        private void wpInstallation_PageValidating(object sender, ValidatingEventArgs e)
        {
            if (firstOnNext)
            {
                // stop the TV4Home.Server.CoreService, so it doesn't interfere with installation
                StartStopTV4HomeCoreService(false);

                // disable all buttons
                this.EnableButtons(false, false, false);
                this.CloseDisabled = true;

                try
                {
                    // perform the installation
                    installSucceeded = wpInstallation.InstallComponents();
                }
                catch (Exception ex)
                {
                    TaskMessageBox.Show(ex.Message + ex.StackTrace, "Error", "An error has occured!", TaskDialogButtons.Ok, TaskDialogIcon.Error);
                }

                this.WizardNextButton.Text = nextButtonText;
                this.WizardNextButton.Enabled = true;

                this.CloseDisabled = false;

                firstOnNext = false;

                // don't move to next page yet, user might want to check status in listview and then press Next
                e.IsValid = false;

                // start the previously stopped TV4Home.Server.CoreService again
                StartStopTV4HomeCoreService(true);
            }
        }

        private void wpInstallation_GettingNextPage(object sender, GettingTargetPageEventArgs e)
        {
            if (installSucceeded)
                e.TargetPage = wpFinished;
            else
                e.TargetPage = wpFinishedError;
        }

        private void StartStopTV4HomeCoreService(bool start)
        {
            ServiceController service = new ServiceController("TV4HomeCoreService");

            try
            {
                TimeSpan timeout = TimeSpan.FromSeconds(3);

                if (start)
                {
                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
                }
                else
                {
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                }
            }
            catch (Exception ex)
            {
                //TODO: log exception
            }
        }
        #endregion

        #region WPFinished
        private void wpFinished_PageEnter(object sender, EventArgs e)
        {
            this.SetButtonsVisibility(true, false, true);
            this.EnableButtons(false, false, true);
            this.WizardCancelButton.Text = "Done";
        }
        #endregion

        #region WPFinishedError
        private void wpFinishedError_PageEnter(object sender, EventArgs e)
        {
            this.SetButtonsVisibility(true, false, true);
            this.EnableButtons(false, false, true);
            this.WizardCancelButton.Text = "Done";
        }
        #endregion
    }
}
